using System;
using FrameOperateSync;
using UnityEngine;
using Unity.Collections;
#if UNITY_EDITOR

[RequireComponent(typeof(ISyncNetwork)),DisallowMultipleComponent]
public sealed class UnityFrameEditorRender : MonoBehaviour,IFrameLoger,IFrameParser
{
    [SerializeField]
    private bool delayModeToggle;
    [SerializeField]
    private bool logDelayToggle;
    [SerializeField]
    private int setFixDelayInput;
    [SerializeField]
    private int setWaveDelayInput;

    void OnEditorUpdate()
    {
        //RenderUtility.GameFixedUpdaterRender();
    }

    private void Awake()
    {
        if (!Application.isEditor)
            return;

        var config = ScriptableObject.CreateInstance<SyncFrameConfig>();
        config.siglePlayerMode = true;
        config.networkLagSimulate = delayModeToggle;
        config.logLagInfoFlag = logDelayToggle;
        config.networkWaveMax = setWaveDelayInput;
        config.networkLagTime = setFixDelayInput;
        SyncFrameConfig.SetFrameSetting(config);

        HelperUtility.SetLogger(this);
        HelperUtility.SetFrameParser(this);

        var network = GetComponent<ISyncNetwork>();

        ClientUtility.StartSync(network, null, (act) => { act?.Invoke(); });
    }

    private void OnEnable()
    {
        if (!Application.isEditor)
            return;
        if (!Application.isPlaying)
        {
            UnityEditor.EditorApplication.update += OnEditorUpdate;
        }
    }

    private void FixedUpdate()
    {
        //RenderUtility.GameFixedUpdaterRender();
    }

    private void OnDisable()
    {
        if (!Application.isEditor)
            return;
        
        if (!Application.isPlaying)
        {
               UnityEditor.EditorApplication.update -= OnEditorUpdate;
        }
    }

    public void LogInfo(string msg)
    {
        Debug.Log($"SyncInfo:{msg}");
    }

    public void LogWarning(string msg)
    {
        Debug.LogWarning($"SyncWarning:{msg}");
    }

    public void LogError(string msg)
    {
        Debug.Log($"SyncError:{msg}");
    }

    public string ToJson(object data)
    {
        return JsonUtility.ToJson(data);
    }

    public object FromJson(string json, Type type)
    {
        return JsonUtility.FromJson(json, type);
    }
}

#endif